package com.shiyi.aspectj;

import com.shiyi.annotations.DynamicDataSource;
import com.shiyi.contexts.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author wangzhanshuai
 * @date 2021/3/5 3:34 上午
 * @since 1.0
 */
@Aspect
@Order(-1)
@Component
public class DynamicDataSourceAspect {

    @Pointcut(value = "@annotation(com.shiyi.annotations.DynamicDataSource)")
    public void pointCut() {}

    @Around(value = "pointCut() && @annotation(dynamicDataSource)")
    public Object aroundAfter(ProceedingJoinPoint joinPoint, DynamicDataSource dynamicDataSource) {
        Object proceed = null;
        try {
            System.out.println("切换数据源：" + dynamicDataSource.type().getType());
            DynamicDataSourceContextHolder.set(dynamicDataSource.type());
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            DynamicDataSourceContextHolder.clear();
        }
        return proceed;
    }
}
